﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Networking;

public class MoveComponent : NetworkBehaviour
{
    public Transform foot;
    private Rigidbody _rigidbody;
    public int moveSpeed = 5;
    float currentVerticalSpeed = 0f;
    float m_CameraVerticalAngle = 0f;
    public GameObject playerCamera;
    public float rotationSpeed = 2;
    [SerializeField]
    private float jumpPower = 5;
    [SerializeField]
    private float gravity = 10f;
    
    // Start is called before the first frame update
    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        
        //重力速度模拟
        if (!IsGround())
        {
            currentVerticalSpeed -= gravity * Time.deltaTime;
        }
        else
        {
            if (currentVerticalSpeed <= 0f)
                currentVerticalSpeed = 0f;
        }
        _rigidbody.velocity += Vector3.up * currentVerticalSpeed;
    }

    public void Jump()
    {
        if (IsGround())
        {
            currentVerticalSpeed = jumpPower;    
        }
    }

    public void RotateCamera(float mousex, float mousey)
    {
        transform.Rotate(new Vector3(0f, (mousex * rotationSpeed), 0f), Space.Self);
        m_CameraVerticalAngle += mousey * rotationSpeed;
        m_CameraVerticalAngle = Mathf.Clamp(m_CameraVerticalAngle, -89f, 89f);
        playerCamera.transform.localEulerAngles = new Vector3(-m_CameraVerticalAngle, 0, 0);
    }
    
    bool IsGround()
    {
        RaycastHit hitInfo;
        if(Physics.Raycast(foot.position, Vector3.down,out hitInfo,0.05f,LayerMask.GetMask("Ground")))
        {
            if (hitInfo.collider != null)
            {
                return true;
            }
        }
        return false;
    }

    public void Move(float vertical, float horizontal)
    {
        Vector3 move = transform.forward * vertical + transform.right * horizontal;
        _rigidbody.velocity = move * moveSpeed;
    }
}
